import Cookie from "js-cookie";
import { defaultRoutes } from "@/router/index";
import http from "@/api/config";
const homeMenu = {
  path: "/",
  name: "home",
  label: "首页",
  icon: "home"
};
export default {
  state: {
    isCollapse: false,
    menu: [],
    currentMenu: homeMenu,
    tabsList: [],
    crumbList: []
  },
  mutations: {
    setMenu(state, val) {
      state.menu = val;
      Cookie.set("menu", JSON.stringify(val));
      console.log(val, "vuex");
    },
    clearMenu(state) {
      state.menu = [];
      Cookie.remove("menu");
    },
    setCrumbList(state, list) {
      state.crumbList = list;
    },
    clickCollapse(state) {
      state.isCollapse = !state.isCollapse;
    },
    selectMenu(state, val) {
      state.currentMenu = val;
      let result = state.tabsList.findIndex(item => item.name === val.name);
      result === -1 ? state.tabsList.push(val) : "";
    },
    // eslint-disable-next-line no-unused-vars
    addMenu(state, router) {
      // if (!Cookie.get('menu')) {
      //   return
      // }
      // let menu = JSON.parse(Cookie.get('menu'))
      http.post("/permission/getMenu", this.form).then(res => {
        console.log(res, "res");
        let permission = res.data.data.menu;
        let currentMenu = defaultRoutes;
        let menus = [];
        permission.forEach(item => {
          let itemMenu = JSON.parse(JSON.stringify(item));
          itemMenu.children = [];
          item.meta = {
            label: item.label
          };
          item.component = () => import(`@/views/${item.name}`);
          if (item.children) {
            let parentPath = item.path;
            let parentName = item.name;
            item.children = item.children.map(item => {
              if (item.show) {
                itemMenu.children.push(item);
              }
              item.component = () =>
                import(`@/views/${parentName}/${item.name}`);
              item.meta = {
                label: item.label
              };
              item.path = parentPath + item.path;
              return item;
            });
          }
          if (item.show) {
            menus.push(itemMenu);
          }
          currentMenu[0].children.push(item);
        });
        state.menu = menus;
        router.addRoutes(currentMenu);
      });
    }
  },
  actions: {}
};
